import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';

/*
* @Package: root_page.home_page.video
* @ClassName: video_play_widget
* @Author: szj
* @CreateDate: 7/31/21 1:37 PM
* 视频播放器: 基于chewie的二次封装
*/
class VideoPlayWidget extends StatefulWidget {
  final String url;
  final bool autoPlay;
  final bool looping;
  final bool allowFullScreen;
  final bool allowPlaybackSpeedChanging;
  final double aspectRatio;

  //是否全屏
  final bool isFullScreen;

  const VideoPlayWidget({
    Key key,
    // 视频播放链接
    @required this.url,
    // 自动播放
    this.autoPlay = true,
    // 循环播放
    this.looping = true,
    // 视频的纵横比--宽/高
    this.aspectRatio = 16 / 9,
    // 是否允许全屏
    this.allowFullScreen = true,
    // 是否允许视频速度的改变
    this.allowPlaybackSpeedChanging = true,
    this.isFullScreen = false,
  }) : super(key: key);

  @override
  _VideoPlayWidgetState createState() => _VideoPlayWidgetState();
}

class _VideoPlayWidgetState extends State<VideoPlayWidget> {
  VideoPlayerController videoPlayerController;

  ChewieController _chewieController;

  @override
  void initState() {
    super.initState();
    videoPlayerController = VideoPlayerController.network(widget.url);

    _chewieController = ChewieController(
      videoPlayerController: videoPlayerController,
      // 自动播放
      autoPlay: widget.autoPlay,
      // 循环播放
      looping: widget.looping,
      // 视频的纵横比--宽/高
      aspectRatio: widget.aspectRatio,
      // 是否允许视频速度的改变
      allowPlaybackSpeedChanging: widget.allowPlaybackSpeedChanging,
      // 是否允许全屏
      allowFullScreen: widget.allowFullScreen,

      // 定义自定义控件(IOS风格)
      customControls: CupertinoControls(
        iconColor: Colors.white,
        backgroundColor: Colors.black54,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return !widget.isFullScreen
        ? _body()
        : Scaffold(
            body: _body(),
          );
  }

  Widget _body() {
    return Container(
      padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
      height: !widget.isFullScreen ? 180 : MediaQuery.of(context).size.height,
      width: MediaQuery.of(context).size.width,
      child: Chewie(
        controller: _chewieController,
      ),
    );
  }

  @override
  void dispose() {
    videoPlayerController.dispose();
    _chewieController.dispose();
    super.dispose();
  }
}
